# !/usr/bin/env python
# encoding: utf-8


"""
  @author: gaogao
  @file: wiggle_widget.py
  @time: 2021/6/4 11:53
  @desc:
"""
import PySide6
from PySide6.QtCore import (QByteArray, QFile, QFileInfo, QSaveFile, QSettings,
                            QTextStream, Qt, QBasicTimer, Slot)
from PySide6.QtGui import QAction, QIcon, QKeySequence, QFont, QPalette, QFontMetrics, QPainter, QColor
from PySide6.QtWidgets import (QApplication, QFileDialog, QMainWindow,
                               QMessageBox, QTextEdit, QWidget, QVBoxLayout, QLineEdit)


class WiggleWidget(QWidget):
    def __init__(self, parent=None):
        super(WiggleWidget, self).__init__(parent)
        # 文本
        self.text = "Hello Pyside6"
        # 定时器
        self.basic_timer = QBasicTimer()
        self.step = 0
        self.setBackgroundRole(QPalette.Midlight)
        self.setAutoFillBackground(True)
        self.new_font = QFont()
        self.new_font.setPointSize(self.new_font.pointSize() + 20)
        self.setFont(self.new_font)
        self.basic_timer.start(60, self)

    @Slot()
    def set_text(self, value):
        self.text = value

    # QPainter绘制操作实在QWIdget.painEvent()中完成的，且绘制方法必须在QtGui.QPainter对象的begin()和end()之间。
    def paintEvent(self, event: PySide6.QtGui.QPaintEvent) -> None:
        sina = [0, 38, 71, 92, 100, 92, 71, 38, 0, -38, -71, -92, -100, -92, -71, -38]
        metrics = QFontMetrics(self.font())
        x = (self.width() - metrics.horizontalAdvance(self.text)) / 2
        y = (self.height() + metrics.ascent() - metrics.descent()) / 2
        color = QColor()
        painter = QPainter()
        # 设置抗锯齿
        painter.setRenderHint(QPainter.Antialiasing)
        # 开始在目标设备上绘图
        painter.begin(self)
        self.drawText(painter, x, y, sina, color, metrics)
        painter.end()

    def drawText(self, painter, x, y, sina, color, metrics):
        for i in range(len(self.text)):
            index = (self.step + i) % 16
            color.setHsv((15 - index) * 16, 255, 191)
            painter.setPen(color)
            painter.drawText(x, y - ((sina[index] * metrics.height()) / 400), self.text[i])
            x += metrics.horizontalAdvance(self.text[i])

    def timerEvent(self, event: PySide6.QtCore.QTimerEvent) -> None:
        if event.timerId() == self.basic_timer.timerId():
            self.step += 1
            self.update()
        else:
            QWidget.timerEvent(event)
